package com.ctshk.rpc.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.GlobalConstants;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.CharUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.ShareCodeUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.goods.dto.ShoppingShopStoreDTO;
import com.ctshk.rpc.goods.dto.ShoppingShopStoreDetailedDTO;
import com.ctshk.rpc.goods.dto.ShoppingShopStoreDetailedTitleDTO;
import com.ctshk.rpc.goods.entity.ShoppingShopStore;
import com.ctshk.rpc.goods.mapper.ShoppingShopStoreMapper;
import com.ctshk.rpc.goods.req.ShoppingShopStoreAddReq;
import com.ctshk.rpc.goods.req.ShoppingShopStorePageReq;
import com.ctshk.rpc.goods.req.ShoppingShopStoreUpdateStatusReq;
import com.ctshk.rpc.goods.service.IShoppingShopStoreService;
import com.ctshk.rpc.system.service.ISysPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 小店管理 服务实现类
 * </p>
 *
 * @author 姜斌文
 * @since 2021-04-07
 */
@Slf4j
@DubboService
public class ShoppingShopStoreServiceImpl extends ServiceImpl<ShoppingShopStoreMapper, ShoppingShopStore> implements IShoppingShopStoreService {
	
	@Autowired
	private ShoppingShopStoreMapper ShopStoreMapper;

	@DubboReference
	private ISysPermissionService sysPermissionService;

	@Override
	public void addShoppingShopStore(ShoppingShopStoreAddReq shopStoreAddReq, Long userId) {
		ShoppingShopStore shopStore = new ShoppingShopStore();
		BeanUtils.copyProperties(shopStoreAddReq, shopStore);
		if(shopStoreAddReq.getStaffId() != null){
			String storeInvitationCode = ShareCodeUtil.idToCode(shopStoreAddReq.getStaffId()); // 邀请码
			shopStore.setStoreInvitationCode(storeInvitationCode);
		}else{
			shopStore.setStoreInvitationCode(CharUtil.getNumber(6, 0).toUpperCase());
		}
		LocalDateTime now=LocalDateTime.now();
		Long id = SnowflakeIdWorker.nextId();
		shopStore.setId(id);
		shopStore.setCreateId(userId);
		shopStore.setGmtCreate(now);
		shopStore.setModifiedId(userId);
		shopStore.setGmtModified(now);
//		shopStore.setStoreUrl("http://47.119.156.244:9096/"+);
		shopStore.setStoreUrl("https://m.ctshk.com/"+shopStore.getShopId()+File.separator+shopStore.getStoreInvitationCode());
		shopStore.setIsDeleted(IsDeletedCode.NO.getCode());
		shopStore.setStatus(1); // 	0：无效;	1：有效
		ShopStoreMapper.insert(shopStore);
	}

	@Override
	public void addShoppingShopStoreMember(ShoppingShopStoreAddReq shopStoreAddReq, Long userId) {
		ShoppingShopStore shopStore = new ShoppingShopStore();
		String storeInvitationCode = ShareCodeUtil.idToCode(userId); // 邀请码
		BeanUtils.copyProperties(shopStoreAddReq, shopStore);
		LocalDateTime now=LocalDateTime.now();
		shopStore.setId(SnowflakeIdWorker.nextId());
		if(userId != 0){
			shopStore.setStoreInvitationCode(storeInvitationCode);
		}else{
			// 外部人员生成随机的邀请码
			shopStore.setStoreInvitationCode(CharUtil.getNumber(6, 0).toUpperCase());
		}
		shopStore.setStoreId(shopStoreAddReq.getId());
		shopStore.setCreateId(userId);
		shopStore.setGmtCreate(now);
		shopStore.setModifiedId(userId);
		shopStore.setGmtModified(now);
		shopStore.setIsDeleted(IsDeletedCode.NO.getCode());
		shopStore.setStaffType(2); // 	固定2,2为成员
		shopStore.setStatus(1); // 	0：无效;	1：有效
		shopStore.setStoreType(2); // 固定2,2为分店
		ShopStoreMapper.insert(shopStore);
	}

	@Override
	public void updateShoppingShopStore(ShoppingShopStoreAddReq shopStoreAddReq, Long userId) {
		ShoppingShopStore shopStore = ShopStoreMapper.selectById(shopStoreAddReq.getId());
        BeanUtils.copyProperties(shopStoreAddReq, shopStore, EntityUtil.getNullPropertyNames(shopStoreAddReq));
		LocalDateTime now=LocalDateTime.now();
		shopStore.setModifiedId(userId);
		shopStore.setGmtModified(now);
		ShopStoreMapper.updateById(shopStore);
	}

	@Override
	public void updateShoppingShopStoreStatus(
			ShoppingShopStoreUpdateStatusReq shopStoreUpdateReq, Long userId) {
		if (null != shopStoreUpdateReq && null != shopStoreUpdateReq.getId() && null != shopStoreUpdateReq.getStatus()) {
			ShoppingShopStore shopStore = ShopStoreMapper.selectById(shopStoreUpdateReq.getId());
			if (Objects.isNull(shopStore)) {
				throw new BusinessException(SystemError.MALL_MERCHANDISE_23036);
			}
	        BeanUtils.copyProperties(shopStoreUpdateReq, shopStore, EntityUtil.getNullPropertyNames(shopStoreUpdateReq));
			LocalDateTime now=LocalDateTime.now();
			shopStore.setModifiedId(userId);
			shopStore.setGmtModified(now);
			ShopStoreMapper.updateById(shopStore);
		}
	}

	@Override
	public PageResponse<ShoppingShopStoreDTO> findShoppingShopStoreByCondition(ShoppingShopStorePageReq pageReq, TokenUser tokenUser) {
		Result<List<Long>> permissionResult = sysPermissionService.queryPermission(pageReq.getMenuId(), tokenUser.getId());
		if (!permissionResult.isSuccess()) {
			SystemError result = SystemError.getDefined(permissionResult.getCode());
			throw new BusinessException(result);
		}
		//不是管理员
		if (!GlobalConstants.Role.isAdmin(tokenUser.getUsername())) {
			pageReq.setIsNotAdmin(1);
			String ids = "";
			List<Long> data = permissionResult.getData();
			if(data != null && data.size() >0){
				for (Long datum : data) {
					ids += datum + ",";
				}
			}
			if(ids.length() > 0){
				ids = ids.substring(0, ids.length() - 1);
			}
			pageReq.setUserIds(ids);
		}
		IPage<ShoppingShopStoreDTO> page = new Page<ShoppingShopStoreDTO>(pageReq.getPageNo(),pageReq.getPageSize());
		IPage<ShoppingShopStoreDTO> iPage = ShopStoreMapper.findShoppingShopStoreByCondition(page, pageReq);
		List<ShoppingShopStoreDTO> shoppingShopStoreList = iPage.getRecords();
		List<ShoppingShopStoreDTO> pageDTOList = EntityUtil.copyList(shoppingShopStoreList, ShoppingShopStoreDTO.class);
		return new PageResponse<>(pageDTOList, iPage.getCurrent() == 1,
				iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
				iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
	}

	@Override
	public ShoppingShopStoreDetailedTitleDTO findShoppingShopStoreById(
			ShoppingShopStorePageReq req, TokenUser tokenUser) {
		log.info("【中旅商城--B端--查询小店明细--start】，入参为:{}", JSON.toJSONString(req));
		ShoppingShopStore shopStore = ShopStoreMapper.selectById(req.getId());
		log.info("【中旅商城--B端--根据id查询小店明细】，返参为:{}", JSON.toJSONString(shopStore));
		ShoppingShopStoreDetailedTitleDTO detailedTile = new ShoppingShopStoreDetailedTitleDTO();
		if (null != shopStore) {
	        BeanUtils.copyProperties(shopStore, detailedTile, EntityUtil.getNullPropertyNames(shopStore));
	        
	        IPage<ShoppingShopStoreDetailedDTO> page = new Page<ShoppingShopStoreDetailedDTO>(req.getPageNo(),req.getPageSize());
	        req.setId(shopStore.getId());
	        req.setStoreId(shopStore.getId());
			IPage<ShoppingShopStoreDetailedDTO> iPage = ShopStoreMapper.findShoppingShopStoreDetailedByCondition(page, req);
			log.info("【中旅商城--B端--条件查询小店明细】，返参为:{}", JSON.toJSONString(iPage.getRecords()));
			List<ShoppingShopStoreDetailedDTO> storeDetailedList = iPage.getRecords();
			List<ShoppingShopStoreDetailedDTO> pageDTOList = EntityUtil.copyList(storeDetailedList, ShoppingShopStoreDetailedDTO.class);
			PageResponse<ShoppingShopStoreDetailedDTO> pageResult =  new PageResponse<ShoppingShopStoreDetailedDTO>(pageDTOList, iPage.getCurrent() == 1,
					iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
					iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
			detailedTile.setTotalMemberNumber(Integer.valueOf((int) iPage.getTotal()));
			detailedTile.setDetailedList(pageResult);
		}
		log.info("【中旅商城--B端--查询小店明细--end】");
		return detailedTile;
	}

	@Override
	public ShoppingShopStoreDTO findShoppingShopStoreDetailById(Long id, TokenUser tokenUser) {
		log.info("【中旅商城--根据ID查询小店详细信息--start】，入参为:{}",id);
		ShoppingShopStore shoppingShopStore = ShopStoreMapper.findShoppingShopStoreDetailById(id);
		ShoppingShopStoreDTO shoppingShopStoreDTO = new ShoppingShopStoreDTO();
		if(shoppingShopStore != null){
			BeanUtils.copyProperties(shoppingShopStore, shoppingShopStoreDTO);
		}
		log.info("【中旅商城--根据ID查询小店详细信息--end】");
		return shoppingShopStoreDTO;
	}
}
